package routers

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"go-vue/admin/adapt"
	"go-vue/admin/conf"
	"go-vue/admin/utils"
	"strings"
)

// CheckJwt 校验头部信息
func CheckJwt(ctx *gin.Context) {
	authorization := ctx.GetHeader("Authorization")
	//判断权限
	if len(authorization) == 0 {
		ctx.Abort()
		utils.LoginOut(ctx)
		//utils.OutWrong(ctx, adapt.JwtNoLogin, "无授权信息", nil)
		return
	}

	claims, err := adapt.ParseToken(strings.Replace(authorization, adapt.JwtPreString, "", 1))
	if err != nil {
		ctx.Abort()
		utils.LoginOut(ctx)
		//utils.OutWrong(ctx, adapt.JwtNoLogin, "登录信息已失效", err)
		return
	}

	//超过一定时间90s，重新生成Token
	if claims.IssuedAt+90 < utils.DateNowTime() {
		token, err := adapt.CreateJwt(claims.Id, claims.Audience)
		if err == nil {
			ctx.Set("NewAuthorization", token)
		}
	}

	//设置用户id
	userInfo := adapt.GetPermissionMenu(cast.ToInt64(claims.Id))
	if userInfo.Err != nil {
		ctx.Abort()
		utils.LoginOut(ctx)
		return
	}

	//用户状态不正确
	if userInfo.State != conf.StateOn {
		ctx.Abort()
		utils.LoginOut(ctx)
		return
	}

	//设置用户信息
	ctx.Set("UserInfo", userInfo)

	ctx.Next()
}
